import { Color, defined, Event, JulianDate, Material, Property, Viewer } from "cesium";
import MaterialProperty from "cesium/Source/DataSources/MaterialProperty";
import { guid } from "./utils/misc";

export class MaterialUtils {
    constructor(private viewer: Viewer) {

    }
    getPolylineTrailLinkMaterialProperty(duration: number, image: string) {
        const materialType = 'PolylineTrailLink' + guid();
        const curTime = (new Date()).getTime();
        (Material as any)._materialCache.addMaterial(materialType, {
            fabric: {
                type: materialType,
                uniforms: {
                    color: new Color(0.0, 0.0, 1.0, 0.5),
                    image: image,
                    time: 20
                },
                source: "czm_material czm_getMaterial(czm_materialInput materialInput)\n\
                {\n\
                    czm_material material = czm_getDefaultMaterial(materialInput);\n\
                    vec2 st = materialInput.st;\n\
                    vec4 colorImage = texture2D(image, vec2(fract(st.s - time), st.t));\n\
                    material.alpha = colorImage.a * color.a;\n\
                    material.diffuse = (colorImage.rgb+color.rgb)/2.0;\n\
                    return material;\n\
                }"
            },
            translucent: function (material: any) {
                return true;
            }
        });
        class PolylineTrailLinkMaterialProperty {
            isConstant: boolean = false;
            definitionChanged: Event<(...args: any[]) => void> = new Event();
            constructor() {
            }
            getType(time: JulianDate): string {
                return materialType;
            }
            getValue(time: JulianDate, result?: any) {
                if (!defined(result)) {
                    result = {};
                }
                result.color = (Property as any).getValueOrClonedDefault(undefined, time, Color.WHITE, result.color);
                result.image = image;
                result.time = (((new Date()).getTime() - curTime) % duration) / duration;
                return result;
            }
            equals(other?: Property | undefined): boolean {
                return this === other ||
                    (other instanceof PolylineTrailLinkMaterialProperty &&
                    // @ts-ignore
                        (Cesium.Property as any).equals(Color.WHITE, other._color))
            }
        }
        const materialProperty = new PolylineTrailLinkMaterialProperty();
        return materialProperty as MaterialProperty;
    }
}
